package cn.fansunion.leecode.linkedlist;

/**
 * 206.反转链表<br/>
 * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。<br/>
 * https://leetcode-cn.com/problems/reverse-linked-list/
 * 
 * @author wen.lei@brgroup.com
 *
 *         2022-2-18
 */
public class ReverseLinkedList {
    /*   输入：head = [1,2,3,4,5]
        输出：[5,4,3,2,1]
            输入：head = [1,2]
                输出：[2,1]
                示例 3：
    
                输入：head = []
                输出：[]*/
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        // 第1个prev，默认为头结点
        ListNode prev = head;
        ListNode next = head.next;
        // 关键点2：头结点的next需要改为null，不然“循环链表543212345”
        head.next = null;
        // 关键点1：维护一个尾节点
        ListNode foot = head;
        while (next != null) {
            foot = next;
            next = next.next;
            foot.next = prev;
            prev = foot;
        }
        return foot;

    }
}
